package hero.mps.web.school_college.cotroller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import hero.mps.utils.ResultUtils;
import hero.mps.utils.ResultVo;
import hero.mps.web.school_college.entity.CollegeParam;
import hero.mps.web.school_college.entity.SchoolCollege;
import hero.mps.web.school_college.service.SchoolCollegeService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/api/college")
@RequiredArgsConstructor
public class SchoolCollegeController {
    private final SchoolCollegeService schoolCollegeService;

    @PostMapping
    public ResultVo add(@RequestBody SchoolCollege schoolCollege) {
        schoolCollege.setCreateData(new Date());
        boolean save = schoolCollegeService.save(schoolCollege);
        if (save) {
            return ResultUtils.success("新增学院成功");
        }else {
            return ResultUtils.error("新增学院失败");
        }
    }
    @PutMapping
    public ResultVo update(@RequestBody SchoolCollege schoolCollege) {
        boolean update = schoolCollegeService.updateById(schoolCollege);
        if (update) {
            return ResultUtils.success("更新学院成功");
        }else {
            return ResultUtils.error("更新学院失败");
        }
    }

    @DeleteMapping("/{collegeId}")
    public ResultVo delete(@PathVariable("collegeId") Integer collegeId) {
        boolean delete = schoolCollegeService.removeById(collegeId);
        if (delete) {
            return ResultUtils.success("删除学院成功");
        }else {
            return ResultUtils.error("删除学院失败");
        }
    }

    @GetMapping("/list")
    public ResultVo list(CollegeParam collegeParam){
//        @RequestParam(required = false) String collegeName,
//    @RequestParam(defaultValue = "1") Long currentPage,
//    @RequestParam(defaultValue = "10") Long pageSize
        // 构造查询条件
        QueryWrapper<SchoolCollege> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(collegeParam.getCollegeName())){
            queryWrapper.lambda().like(SchoolCollege::getCollegeName, collegeParam.getCollegeName());
        }
        queryWrapper.lambda().orderByAsc(SchoolCollege::getOrderNum);
//        构建分页对象
        IPage page = new Page(collegeParam.getCurrentPage(), collegeParam.getPageSize());
//        查询
        IPage list = schoolCollegeService.page(page, queryWrapper);
        return ResultUtils.success("查询成功", list);
    }

}
